<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="会话状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="会话状态" clearable style="width: 200px">
            <el-option label="活跃" value="ACTIVE" />
            <el-option label="已结束" value="ENDED" />
            <el-option label="已暂停" value="PAUSED" />
          </el-select>
        </el-form-item>
        <el-form-item label="AI模型" prop="modelType">
          <el-select v-model="queryParams.modelType" placeholder="AI模型" clearable style="width: 200px">
            <el-option label="GPT-3.5" value="GPT35" />
            <el-option label="GPT-4" value="GPT4" />
            <el-option label="Claude" value="CLAUDE" />
            <el-option label="文心一言" value="ERNIE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="Download"
            class="toolbar-button is-warning"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- AI聊天会话表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="sessionList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="会话ID" align="center" prop="sessionId" width="120" />
        <el-table-column label="用户名" align="center" prop="username" width="120" />
        <el-table-column label="AI模型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getModelType(scope.row.modelType)">
              {{ getModelText(scope.row.modelType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="消息数量" align="center" prop="messageCount" width="100" />
        <el-table-column label="会话时长" align="center" prop="duration" width="120">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="info"
                icon="View"
                @click="handleView(scope.row)"
                class="table-operation-button is-info"
                size="small"
              >查看</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button 
                  type="warning" 
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleMessages" icon="ChatDotRound">消息记录</el-dropdown-item>
                    <el-dropdown-item command="handleStatistics" icon="DataAnalysis">使用统计</el-dropdown-item>
                    <el-dropdown-item command="handleExportSession" icon="Download">导出会话</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 会话详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="会话详情" width="800px">
      <div class="session-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="会话ID">{{ currentSession.sessionId }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentSession.username }}</el-descriptions-item>
          <el-descriptions-item label="AI模型">{{ getModelText(currentSession.modelType) }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getStatusText(currentSession.status) }}</el-descriptions-item>
          <el-descriptions-item label="消息数量">{{ currentSession.messageCount }}</el-descriptions-item>
          <el-descriptions-item label="会话时长">{{ formatDuration(currentSession.duration) }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ parseTime(currentSession.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ parseTime(currentSession.endTime) }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="session-messages" style="margin-top: 20px;">
          <h4>最近消息</h4>
          <div class="message-list">
            <div 
              v-for="message in currentSession.recentMessages"
              :key="message.id"
              class="message-item"
              :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }"
            >
              <div class="message-header">
                <span class="message-role">{{ message.role === 'user' ? '用户' : 'AI' }}</span>
                <span class="message-time">{{ parseTime(message.createTime) }}</span>
              </div>
              <div class="message-content">{{ message.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getChatSessions, deleteChatSession, getChatSessionDetail } from '@/api/aiChat'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const sessionList = ref([])
const queryFormRef = ref()
const showDetailDialog = ref(false)
const currentSession = ref({})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: undefined,
  status: undefined,
  modelType: undefined
})

// 获取会话列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getChatSessions(queryParams)
    if (response.code === 200) {
      sessionList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取会话列表失败')
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    ElMessage.error('获取会话列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 查看会话详情
const handleView = async (row) => {
  try {
    const response = await getChatSessionDetail(row.sessionId)
    if (response.code === 200) {
      currentSession.value = response.data
      showDetailDialog.value = true
    }
  } catch (error) {
    console.error('获取会话详情失败:', error)
    ElMessage.error('获取会话详情失败')
  }
}

// 删除按钮操作
const handleDelete = (row) => {
  const sessionIds = row.sessionId ? [row.sessionId] : ids.value
  ElMessageBox.confirm('是否确认删除会话编号为"' + sessionIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteChatSession(sessionIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除会话失败:', error)
      ElMessage.error('删除会话失败')
    }
  }).catch(() => {})
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleMessages':
      handleMessages(row)
      break
    case 'handleStatistics':
      handleStatistics(row)
      break
    case 'handleExportSession':
      handleExportSession(row)
      break
    default:
      break
  }
}

// 消息记录
const handleMessages = (row) => {
  // 跳转到消息记录页面
  ElMessage.info('跳转到消息记录页面')
}

// 使用统计
const handleStatistics = (row) => {
  // 显示使用统计
  ElMessage.info('显示使用统计')
}

// 导出会话
const handleExportSession = (row) => {
  ElMessage.info('导出会话功能开发中...')
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 工具函数
const getModelType = (modelType) => {
  const typeMap = {
    'GPT35': 'success',
    'GPT4': 'warning',
    'CLAUDE': 'info',
    'ERNIE': 'danger'
  }
  return typeMap[modelType] || 'info'
}

const getModelText = (modelType) => {
  const textMap = {
    'GPT35': 'GPT-3.5',
    'GPT4': 'GPT-4',
    'CLAUDE': 'Claude',
    'ERNIE': '文心一言'
  }
  return textMap[modelType] || modelType
}

const getStatusType = (status) => {
  const typeMap = {
    'ACTIVE': 'success',
    'ENDED': 'info',
    'PAUSED': 'warning'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'ACTIVE': '活跃',
    'ENDED': '已结束',
    'PAUSED': '已暂停'
  }
  return textMap[status] || status
}

// 格式化时长
const formatDuration = (duration) => {
  if (!duration) return '0分钟'
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.session-detail {
  .message-list {
    max-height: 400px;
    overflow-y: auto;
    
    .message-item {
      margin-bottom: 16px;
      padding: 12px;
      border-radius: 8px;
      
      &.user-message {
        background: #e3f2fd;
        margin-left: 20px;
      }
      
      &.ai-message {
        background: #f5f5f5;
        margin-right: 20px;
      }
      
      .message-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 12px;
        color: #666;
        
        .message-role {
          font-weight: 600;
        }
      }
      
      .message-content {
        line-height: 1.5;
      }
    }
  }
}

.table-operation-wrapper {
  display: flex !important;
  flex-wrap: wrap !important;
  gap: 5px;
  justify-content: center;
  align-items: center !important;
  margin: -4px !important;
}
</style>
